package com.sctvcloud.qingchuan.ui.activities;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;

import com.blankj.utilcode.util.ActivityUtils;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseDetailActivity;
import com.sctvcloud.qingchuan.beans.NewsClickCountBean;
import com.sctvcloud.qingchuan.beans.NewsIdBean;
import com.sctvcloud.qingchuan.beans.NewsItem;
import com.sctvcloud.qingchuan.beans.NewsListClickRequestBean;
import com.sctvcloud.qingchuan.beans.NewsListClickVo;
import com.sctvcloud.qingchuan.http.AbsListNetCallback;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.adapter.CultureTravelAdapter;
import com.sctvcloud.qingchuan.ui.util.IListShowData;
import com.sctvcloud.qingchuan.ui.utils.TitleUtils;
import com.sctvcloud.qingchuan.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 快讯公告
 */
public class QuickActivity extends BaseDetailActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    public static final String DATA_URL = "data_url";
    private CultureTravelAdapter adapter;

    private List<IListShowData> newsList = new ArrayList<>();
    private boolean isReset;
    private Handler handler;

    private boolean isRefresh = false;
    private int newsIndex = 0;
    private int newsPageAll = 1;
    private String channelUrl;

    public static void start(String channelUrl) {
        Bundle extras = new Bundle();
        extras.putString(DATA_URL, channelUrl);
        ActivityUtils.startActivity(extras, QuickActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("重要公告");
        handler = new Handler();
        channelUrl = getIntent().getExtras().getString(DATA_URL);
        initViews();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_quick);
        ButterKnife.bind(this);
    }


    @Override
    public void onLoadMore() {
        if (newsIndex < newsPageAll - 1) {
            if (!getNewsList(newsIndex + 1)) {
            }
        } else {
            refreshLayout.setLoadMoreEnabled(false);
        }
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        newsList.clear();
        //首次加载数据，或之后下拉刷新
        boolean b = getNewsList(0);
    }

    private void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();

    }

    /**
     * 获取新闻数据
     */
    private boolean getNewsList(final int index) {
        if (TextUtils.isEmpty(channelUrl)) {
            onNetFinish();
            return false;
        }
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), channelUrl, index, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                newsPageAll = getPageResponse().getData().getPageAll();
                if (ListUtils.isListValued(newsItems)) {
                    newsIndex = index;
                    /***新闻数据请求完成之后获取相应的点击量***/
                    requestNewsClickCount(newsItems);

                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (newsIndex >= newsPageAll - 1) {
                    refreshLayout.setLoadMoreEnabled(false);
                } else {
                    refreshLayout.setLoadMoreEnabled(true);
                }
                onNetFinish();
            }

            @Override
            public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                return super.doInBackground(newsItems);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
        return true;
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(newsIndex + 1 < newsPageAll);
    }

    private List<NewsItem> newsItems;

    /**
     * 获取新闻列表点击量
     */
    private void requestNewsClickCount(List<NewsItem> list) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) != null) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            newsBean.setId(item.getNewsId());
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                }
                newsBean.setType(type);
                newsIdList.add(newsBean);
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) != null) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else if (countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                        ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (isRefresh) {
                            isReset = true;
                            newsList.addAll(newsItems);
                            isRefresh = false;
                        } else {
                            newsList.addAll(newsItems);
                        }
                        onNetFinish(0);//暂时使用calledIndex来保存mode
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }


    private synchronized void onNetFinish(int mode) {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        if (adapter == null) {
            adapter = new CultureTravelAdapter(this, newsList);
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "精选"));
            adapter.setActivity(this);
            adapter.setPairs(pairs);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setDatass(newsList);
        }
        if (isReset) {
            isReset = false;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    recyclerView.smoothScrollToPosition(0);
                }
            }, 700);
        }
    }
}

